package com.jews.framework.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.jews.framework.json.JsonUtils;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * 监听类，可以自定义
 *
 * @author JewsChen
 * @title: ExcelListener
 * @date 2023/2/2 17:38
 */
@Getter
@Slf4j
public class ExcelListener<T> extends AnalysisEventListener<T> {

    private final List<T> result = new ArrayList<>();

    private Map<Integer, String> header = new HashMap<>();

    /**
     * 异常日志记录(可用于记录解析excel数据时存储异常信息，用于业务的事务的回滚)
     */
    private final List<String> errorLogList = new ArrayList<>();

    /**
     * 通过 AnalysisContext 对象还可以获取当前 sheet，当前行等数据
     */
    @Override
    public void invoke(T o, AnalysisContext analysisContext) {
        result.add(o);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("所有数据解析完成！ 解析一共解析{}条数据", result.size());
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            String errorLog = "第" + excelDataConvertException.getRowIndex() + "行，第" + excelDataConvertException.getColumnIndex()
                    + "列解析异常，数据为:" + excelDataConvertException.getCellData().getStringValue() + "";
            log.error(errorLog);
            errorLogList.add(errorLog);
        }
        super.onException(exception, context);
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        this.header = headMap;
        log.info("解析到一条头数据:{}", JsonUtils.getInstance().toJsonString(headMap));
    }
}
